package com.sirdc.modules.sys.web.login;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.util.MD5;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.MessageList;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.EarlyWarningNodeFilter;
import net.huashitong.Project.filter.MessageListFilter;
import net.huashitong.Project.filter.NewProjectsFilter;
import net.huashitong.Project.service.EarlyWarningNodeService;
import net.huashitong.Project.service.MessageListService;
import net.huashitong.Project.service.NewProjectsService;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.oversee.entity.Coordinate;
import net.huashitong.oversee.filter.CoordinateFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.CoordinateService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.databean.BnpUserDatabean;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.filter.BnpUserFilter;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.LoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/newlogin")
public class newLoginController extends JsonBaseController {
    @Autowired
    private NewProjectsService ns;
    @Autowired
    private BnpUserService bs;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private EarlyWarningNodeService earlyWarningNodeService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    private CoordinateService coordinateService;

    @Override
    protected String getView(String s) {
        return null;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String goLonin() {
        return "/modules/login/login";
    }

    /**
     * 登录权限跳转
     *
     * @param model
     * @param response
     * @param request
     * @return
     */

    @RequestMapping(value = "/gologin", method = RequestMethod.POST)
    public String goLonin(@ModelAttribute BnpUserFilter filter, Model model, HttpServletResponse response, HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        if (password.length() < 8) {
//            model.addAttribute("mgs", "密码长度不小于8位");
//            return "/modules/login/login";
//        } else {
//            String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
//            if (!password.matches(regex)) {
//                model.addAttribute("mgs", "密码必须大小写数字混合");
//                return "/modules/login/login";
//            }
//        }
        password = MD5.parseMD5(password);
        BnpUser bnpUser = bs.getBnpUser(username, password);
        if (ObjectUtils.isBlank(bnpUser)) {
            bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        }
        if (ObjectUtils.isNotBlank(bnpUser)) {
            model.addAttribute("bnpUser", bnpUser);
            WebUtils.setSessionAttribute(request, "user", bnpUser);
            // 记录登录日志
            loginLogService.doLoginLog(bnpUser);

            //我的督查
            SupervisionTaskFilter taskFilter = new SupervisionTaskFilter();
            taskFilter.setUserinfo(bnpUser.getPhone());
            taskFilter.setBranchType(bnpUser.getBranchType());
            taskFilter.setRole(bnpUser.getRole());
            taskFilter.setValid("1");
            int myTaskNum = supervisionTaskService.getMissinTaskCount(taskFilter);
            model.addAttribute("myTaskNum", myTaskNum);

            //攻坚任务
            SupervisionTaskFilter taskFilter1 = new SupervisionTaskFilter();
            taskFilter1.setUserinfo(bnpUser.getPhone());
            taskFilter1.setBranchType(bnpUser.getBranchType());
            taskFilter1.setRole(bnpUser.getRole());
            taskFilter1.setValid("1");
            taskFilter1.setTackFlag("1");
            int myTackTaskNum = supervisionTaskService.getMissinTaskCount(taskFilter1);
            WebUtils.setSessionAttribute(request, "myTackTaskNum", myTackTaskNum);
            model.addAttribute("myTackTaskNum", myTackTaskNum);

            //我的协调
            CoordinateFilter coordinateFilter = new CoordinateFilter();
            coordinateFilter.setUserinfo(bnpUser.getPhone());
            coordinateFilter.setBranchType(bnpUser.getBranchType()); //设置查询权限
            if (StringUtils.isBlank(coordinateFilter.getGroupCode())) //督查组权限
            {
                coordinateFilter.setGroupCode(bnpUser.getGroupCode());
            }
            int quetionNum = coordinateService.queryCoordinateCount(coordinateFilter);
            model.addAttribute("quetionNum", quetionNum);
            //保存myTaskNum、保存quetionNum、保存taskMessageList
            WebUtils.setSessionAttribute(request, "myTaskNum", myTaskNum);
            WebUtils.setSessionAttribute(request, "quetionNum", quetionNum);

            NodeNewschedulesFilter filter1 = new NodeNewschedulesFilter();
            filter1.setOperatorUser(bnpUser.getName());
            filter1.setOperatorPhone(bnpUser.getPhone());
            //进行中的小节点个数
            double totalPage12 = (double) nodeNewschedulesService.queryListByFilterZong(filter1).size();
            model.addAttribute("nodeCount", (new Double(totalPage12)).intValue());
            //保存nodeCount
            WebUtils.setSessionAttribute(request, "nodeCount", (new Double(totalPage12)).intValue());

            if ("经办人".equals(bnpUser.getRole())) {
                //跳转业主管理页面
                if ("0".equals(bnpUser.getBranchType())) {
                    model.addAttribute("leftType", "我的项目");
                    return "/modules/myProjects/query";
                    //跳转节点审批管理页面
                } else if ("1".equals(bnpUser.getBranchType())) {
                    double page = ns.getProjectSumPage(null);
                    model.addAttribute("leftType", "确认节点列表");
                    model.addAttribute("totalPage", page);
                    return "/modules/Accraditation/Accraditation_project";
                    //跳转管理界面
                } else if ("2".equals(bnpUser.getBranchType())) {
                    List<BnpUser> list = bs.getUserInfo(filter);
                    model.addAttribute("leftType", "项目管理");
                    double totalPage = bs.getBnpUserSum(filter);
                    model.addAttribute("totalPage", totalPage);
                    //责任单位
                    List<String> deptList = new ArrayList<>();
                    Map<String, BnpUser> deptMap = new HashMap<>();
                    BnpUserFilter bnpUserFilter = new BnpUserFilter();
                    bnpUserFilter.setBranchType("1");
                    bnpUserFilter.setRole("经办人");
                    List<BnpUser> bnpUsers = bs.queryByFilter(bnpUserFilter);
                    for (BnpUser user : bnpUsers) {
                        if (!deptMap.containsKey(user.getBranch())) {
                            deptMap.put(user.getBranch(), user);
                            deptList.add(user.getBranch());
                        }
                    }
                    model.addAttribute("deptList", deptList);
//                    return "/modules/hardWork/user_xmProject";
                    return "/modules/projectManage/query";
                } else if ("3".equals(bnpUser.getBranchType())) {
                    model.addAttribute("dataMap", getData());

                    int a1 = ns.getProjectsByNatureTypeDetail("政府投资房建市政类");
                    int a2 = ns.getProjectsByNatureTypeDetail("政府投资交通水利类");
                    int a3 = ns.getProjectsByNatureTypeDetail("企业投资类");
                    int a4 = ns.getProjectsByNatureTypeDetail("土地收储类");
                    model.addAttribute("a1", a1);
                    model.addAttribute("a2", a2);
                    model.addAttribute("a3", a3);
                    model.addAttribute("a4", a4);
                    return "/modules/index/index_chart";
                } else if ("4".equals(bnpUser.getBranchType())) {
                    model.addAttribute("leftType", "项目管理");
                    EarlyWarningNodeFilter filters = new EarlyWarningNodeFilter();
                    model.addAttribute("warning", earlyWarningNodeService.queryEarlyWarning(filters));
                    model.addAttribute("totalPage", earlyWarningNodeService.querywarningCount(filters));

                    return "/modules/projectManage/query";
                }
            } else if ("责任人".equals(bnpUser.getRole())) {
                model.addAttribute("leftType", "我的项目");
//                NewProjectsFilter npf = new NewProjectsFilter();
//                npf.setOwnerUnitPersonPhone(bnpUser.getPhone());
//                List<NewProjects> nplist = ns.queryByfilter(npf);
//                model.addAttribute("leftType", "我的项目");
//                model.addAttribute("nplist", nplist);
//                return "/modules/OwnerUnit/owner_task";
                return "/modules/myProjects/query";
            } else if ("领导".equals(bnpUser.getRole()) && "6".equals(bnpUser.getBranchType())) {
                //县分管领导界面
                model.addAttribute("leftType", "项目管理");
                return "/modules/projectManage/query";
            } else {
                int a1 = ns.getProjectsByNatureTypeDetail("政府投资房建市政类");
                int a2 = ns.getProjectsByNatureTypeDetail("政府投资交通水利类");
                int a3 = ns.getProjectsByNatureTypeDetail("企业投资类");
                int a4 = ns.getProjectsByNatureTypeDetail("土地收储类");
                model.addAttribute("a1", a1);
                model.addAttribute("a2", a2);
                model.addAttribute("a3", a3);
                model.addAttribute("a4", a4);
                model.addAttribute("dataMap", getData());
                model.addAttribute("bnpUser", bnpUser);
                return "/modules/index/index_chart";
            }
        }
        model.addAttribute("mgs", "用户不存在或者密码错误！");
        return "/modules/login/login";
    }
    //数字峰会，跳过登录页
    /**
     * 登录权限跳转
     *
     * @param model
     * @param response
     * @param request
     * @return
     */

    /*@RequestMapping(value = "/gologin1", method = RequestMethod.GET)
    public String goLonin1(@ModelAttribute BnpUserFilter filter, Model model, HttpServletResponse response, HttpServletRequest request) {
        String username = "18350300651";
        String password = "18350300651";
        password = MD5.parseMD5(password);
        BnpUser bnpUser = bs.getBnpUser(username, password);
        if (ObjectUtils.isBlank(bnpUser)) {
            bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        }
        if (ObjectUtils.isNotBlank(bnpUser)) {
            model.addAttribute("bnpUser", bnpUser);
            WebUtils.setSessionAttribute(request, "user", bnpUser);
            // 记录登录日志
            loginLogService.doLoginLog(bnpUser);
            if ("经办人".equals(bnpUser.getRole())) {
                //跳转业主管理页面
                if ("0".equals(bnpUser.getBranchType())) {
                    NewProjectsFilter npf = new NewProjectsFilter();
                    npf.setUserId(bnpUser.getSysId());
                    List<NewProjects> nplist = ns.queryByfilter(npf);
                    NodeNewschedulesFilter filter1 = new NodeNewschedulesFilter();
                    filter1.setOperatorUser(bnpUser.getName());
                    filter1.setOperatorPhone(bnpUser.getPhone());
                    double totalPage12 = (double) nodeNewschedulesService.queryListByFilterZong(filter1).size();
                    model.addAttribute("nodeCount", (new Double(totalPage12)).intValue());
                    model.addAttribute("leftType", "我的项目");
                    model.addAttribute("nplist", nplist);
                    return "/modules/OwnerUnit/owner_task";
                    //跳转节点审批管理页面
                } else if ("1".equals(bnpUser.getBranchType())) {
                    double page = ns.getProjectSumPage(null);
                    model.addAttribute("leftType", "确认节点列表");
                    model.addAttribute("totalPage", page);
                    NodeNewschedulesFilter filter1=new NodeNewschedulesFilter();
                    filter1.setOperatorUser(bnpUser.getName());
                    filter1.setOperatorPhone(bnpUser.getPhone());
                    double  totalPage12=(double) nodeNewschedulesService.queryListByFilterZong(filter1).size();
                    model.addAttribute("nodeCount",(new Double(totalPage12)).intValue());
                    return "/modules/Accraditation/Accraditation_project";
                    //跳转管理界面
                } else if ("2".equals(bnpUser.getBranchType())) {
                    List<BnpUserDatabean> list = bs.getUserInfo(filter);
                    model.addAttribute("leftType", "用户管理");
                    double totalPage = bs.getBnpUserSum(filter);
                    model.addAttribute("totalPage", totalPage);
//			model.addAttribute("list",list);

                    return "/modules/hardWork/userManger";
                } else if ("3".equals(bnpUser.getBranchType())) {
                    model.addAttribute("dataMap", getData());

                    int a1= ns.getProjectsByNatureTypeDetail("政府投资房建市政类");
                    int a2= ns.getProjectsByNatureTypeDetail("政府投资交通水利类");
                    int a3= ns.getProjectsByNatureTypeDetail("企业投资类");
                    int a4= ns.getProjectsByNatureTypeDetail("土地收储类");
                    model.addAttribute("a1", a1);
                    model.addAttribute("a2", a2);
                    model.addAttribute("a3", a3);
                    model.addAttribute("a4", a4);
                    return "/modules/index/index_chart";
                }else if("4".equals(bnpUser.getBranchType())){
                    model.addAttribute("leftType", "逾期列表");
                    EarlyWarningNodeFilter filters = new EarlyWarningNodeFilter();
                    model.addAttribute("warning", earlyWarningNodeService.queryEarlyWarning(filters));
                    model.addAttribute("totalPage", earlyWarningNodeService.querywarningCount(filters));
                    return "/modules/hardWork/user_warning";

                }
            } else {
                int a1= ns.getProjectsByNatureTypeDetail("政府投资房建市政类");
                int a2= ns.getProjectsByNatureTypeDetail("政府投资交通水利类");
                int a3= ns.getProjectsByNatureTypeDetail("企业投资类");
                int a4= ns.getProjectsByNatureTypeDetail("土地收储类");
                model.addAttribute("a1", a1);
                model.addAttribute("a2", a2);
                model.addAttribute("a3", a3);
                model.addAttribute("a4", a4);
                model.addAttribute("dataMap", getData());
                model.addAttribute("bnpUser", bnpUser);
                return "/modules/index/index_chart";
            }
        }
        model.addAttribute("mgs", "用户不存在或者密码错误！");
        return "/modules/login/login";
    }*/
    //数字峰会，跳过登录页

    /**
     * &#x9996;&#x9875;&#x83b7;&#x53d6;&#x9879;&#x76ee;&#x6570;&#x636e;
     *
     * @return
     */
    private Map<String, Object> getData() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<NewProjects> projects = null;
        NewProjectsFilter filter = new NewProjectsFilter();


        //重点项目
        projects = ns.query();
        int focusProject = projects.size();

        //计划投资
        double plannedInvestment = 0;

        for (NewProjects project : projects) {
            plannedInvestment += Double.parseDouble(StringUtils.isBlank(project.getMoney()) ? "0" : project.getMoney());
        }

        //年度投资计划(暂时写死)
        double annualInvestmentPlan = 150;

        //计划新开工项目年度计划投资
        double planeProjectAnnualPlan = 0;
        filter.setProjectType("2001");//计划新开工项目
        projects = ns.getProjectInfo(filter);
        for (NewProjects project : projects) {
            planeProjectAnnualPlan += Double.parseDouble(StringUtils.isBlank(project.getMoney()) ? "0" : project.getMoney());
        }

        //结转项目年度计划投资
        double jzProjectAnnualPlan = 0;
        filter.setProjectType("2002");//结转项目
        projects = ns.getProjectInfo(filter);
        for (NewProjects project : projects) {
            jzProjectAnnualPlan += Double.parseDouble(StringUtils.isBlank(project.getMoney()) ? "0" : project.getMoney());
        }

        map.put("focusProject", focusProject);
        map.put("plannedInvestment", plannedInvestment);
        map.put("annualInvestmentPlan", annualInvestmentPlan);
        map.put("planeProjectAnnualPlan", planeProjectAnnualPlan);
        map.put("jzProjectAnnualPlan", jzProjectAnnualPlan);
        return map;
    }

    @RequestMapping(value = "/goIndex", method = RequestMethod.GET)
    public String goIndex(Model model, HttpServletResponse response, HttpServletRequest request) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        int a1 = ns.getProjectsByNatureTypeDetail("政府投资房建市政类");
        int a2 = ns.getProjectsByNatureTypeDetail("政府投资交通水利类");
        int a3 = ns.getProjectsByNatureTypeDetail("企业投资类");
        int a4 = ns.getProjectsByNatureTypeDetail("土地收储类");
        model.addAttribute("a1", a1);
        model.addAttribute("a2", a2);
        model.addAttribute("a3", a3);
        model.addAttribute("a4", a4);
        model.addAttribute("bnpUser", bnpUser);
        model.addAttribute("dataMap", getData());
        return "/modules/index/index_chart";
    }

    @RequestMapping(value = "/gologin2", method = RequestMethod.GET)
    public String goLonin2(Model model, HttpServletResponse response, HttpServletRequest request) {
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isNotBlank(bnpUser)) {
            if ("经办人".equals(bnpUser.getRole())) {
                //跳转业主管理页面
                if ("0".equals(bnpUser.getBranchType())) {
                    NewProjectsFilter npf = new NewProjectsFilter();
                    npf.setUserId(bnpUser.getSysId());
                    List<NewProjects> nplist = ns.queryByfilter(npf);
                    model.addAttribute("leftType", "我的项目");
                    model.addAttribute("nplist", nplist);
                    return "/modules/OwnerUnit/owner_task";
                    //跳转节点审批管理页面
                } else if ("1".equals(bnpUser.getBranchType())) {
                    double page = ns.getProjectSumPage(null);
                    model.addAttribute("leftType", "确认节点列表");
                    model.addAttribute("totalPage", page);
                    return "/modules/Accraditation/Accraditation_project";
                    //跳转管理界面
                } else if ("2".equals(bnpUser.getBranchType())) {
                    BnpUserFilter filter = new BnpUserFilter();
                    filter.setName(bnpUser.getName());
                    List<BnpUser> list = bs.getUserInfo(filter);
                    model.addAttribute("leftType", "用户管理");
                    double totalPage = bs.getBnpUserSum(filter);
                    model.addAttribute("totalPage", totalPage);
//			model.addAttribute("list",list);

                    return "/modules/hardWork/userManger";
                } else if ("4".equals(bnpUser.getBranchType())) {
                    model.addAttribute("leftType", "逾期列表");
                    EarlyWarningNodeFilter filters = new EarlyWarningNodeFilter();
                    model.addAttribute("warning", earlyWarningNodeService.queryEarlyWarning(filters));
                    model.addAttribute("totalPage", earlyWarningNodeService.querywarningCount(filters));
                    return "/modules/hardWork/user_warning";

                }
            } else if ("责任人".equals(bnpUser.getRole())) {
                model.addAttribute("leftType", "我的项目");
                EarlyWarningNodeFilter filters = new EarlyWarningNodeFilter();
                model.addAttribute("warning", earlyWarningNodeService.queryEarlyWarning(filters));
                model.addAttribute("totalPage", earlyWarningNodeService.querywarningCount(filters));
                return "/modules/oversee/query";
            } else {
                model.addAttribute("bnpUser", bnpUser);
                model.addAttribute("dataMap", getData());
                return "/modules/index/index_chart";
            }
        }
        return "/modules/login/login";
    }

    @RequestMapping(value = "/goIndex2", method = RequestMethod.GET)
    public String goIndex2(Model model, @RequestParam(required = false, value = "projectType") String projectType,
                           @RequestParam(required = false, value = "sysId") String sysId,
                           @RequestParam(required = false, value = "status") String status,
                           HttpServletRequest request) {
        Object user = WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(user)) {
            return "/modules/login/login";
        } else {
            String firstProjectId;
            if (ObjectUtils.isNotBlank(sysId)) {
                firstProjectId = sysId;
                model.addAttribute("sysId", sysId);
            } else {

                firstProjectId = ns.getFirstProjectIdByType(projectType, status);
            }

            model.addAttribute("status", status);
            model.addAttribute("projectType", projectType);
            model.addAttribute("firstProjectId", firstProjectId);
            return "/modules/index/index_chart_2";
        }
    }

    @RequestMapping(value = "/goIndex3", method = RequestMethod.GET)
    public String goIndex3(Model model, HttpServletResponse response, HttpServletRequest request) {
        Object user = WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(user)) {
            return "/modules/login/login";
        } else {
            return "/modules/index/index_chart_3";
        }

    }

    /**
     * 退出登陆
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/exit", method = RequestMethod.GET)
    public String exit(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        return "/modules/login/login";
    }


    /**
     * 修改密码，验证原密码是否正确
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public Object testIsUserAndPwd(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        BnpUser bnpUser = bs.getBnpUser(username, MD5.parseMD5(password));
        if (bnpUser != null) {
            result.put("valid", true);
            return result;
        } else {
            result.put("valid", false);
            return result;
        }
    }

    /**
     * 修改用户密码
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editPwd", method = RequestMethod.POST)
    public Message editUserPwd(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String newPwd = request.getParameter("newPwd");
        String reNewPwd = request.getParameter("reNewPwd");
        BnpUser bnpUser = bs.getBnpUser(username, MD5.parseMD5(password));
        if (ObjectUtils.isBlank(bnpUser)) {
            return coverMessage("200", "原密码不正确", "0");
        } else {
            if (newPwd.equals(reNewPwd)) {
                //修改密码
                bnpUser.setPassword(MD5.parseMD5(newPwd));
                bs.update(bnpUser);
                return coverMessage("200", "密码修改成功", "1");
            } else {
                return coverMessage("200", "新密码两次输入不一致", "0");
            }

        }

    }

}
